package com.wushi.lenovo.asia5b.app_di.goods.presenter;

import android.text.TextUtils;

import com.mvp.base.BasePresenter;
import com.mvp.base.NetParams;
import com.mvp.base.model.ResultModel;
import com.mvp.common.LocalManageUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.ShopCarFragmentView;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModel;
import com.wushi.lenovo.asia5b.app_model.good.PriceModel;
import com.wushi.lenovo.asia5b.app_model.good.ShopModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_push.PushHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;


/**
 * Created by zhangyuncai on 2019/2/17.
 */
public class ShopCarFragmentPresenter extends BasePresenter<ShopCarFragmentView> {
    ApiService apiService;

    @Inject
    public ShopCarFragmentPresenter(ApiService apiService) {
        this.apiService = apiService;
    }

    /**
     * 获取购物车列表,自营商品
     * todo /cart.get.charges?member_id=929&extra_data=[]&country_id=4&products=[]&source=1&language_code=en&type=marketplace&confirm_order=1 捉取全部购物车里的jawa产品
     */
    public void getGoodListPi(int refresh, List<ShopModel> oldDatas) {
        if (!UserRepository.isLogin()) {
            return;
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("session_id", PushHelper.getRegistrationId() + "");
        map.put("member_id", UserInfo.getMemberId());
        map.put("language_code", LocalManageUtil.getAppLanguage() + "");
        map.put("products", "[]");
        map.put("source", 1);
        map.put("type", "marketplace");
        map.put("country_id", UserInfo.getCountryId());
        map.put("confirm_order", 1);
        map.put("extra_data", "[]");


        Observable<ResultModel<PriceModel>> observable = apiService.getChargesPlaceOrder(map
        );
        baseSubscribe(observable
                , new NetParams(refresh > 1)
                , resultModel -> {
                    if (resultModel.isSuccess() && resultModel.getData() != null && resultModel.getData().shops != null) {
                        notifyAllNewData(resultModel.getData().shops,oldDatas);
                    }else {
                        getView().getShopModelListResult(new ArrayList<>());
                    }
                });
    }

    /**
     * 获取购物车列表,代购商品
     *
     * @param refresh  <=0刷新
     * @param oldDatas 选中的集合
     */
    public void getGoodList(int refresh, List<ShopModel> oldDatas) {
        if (!UserRepository.isLogin()) {
            return;
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("session_id", PushHelper.getRegistrationId() + "");
        map.put("member_id", UserInfo.getMemberId());
        map.put("language_code", LocalManageUtil.getAppLanguage() + "");
        map.put("source", 1);
        map.put("type", "daigou");
        map.put("country_id", UserInfo.getCountryId());
        map.put("products", "[]");
        /**
         * 先调合并购物车接口,然后调购物车接口
         */
        Observable<ResultModel<List<ShopModel>>> observable1 =
                apiService.mergeShopCar(PushHelper.getRegistrationId(), UserInfo.getMemberId())
                        .flatMap(new Function<ResultModel, ObservableSource<ResultModel<List<ShopModel>>>>() {
                            @Override
                            public ObservableSource<ResultModel<List<ShopModel>>> apply(ResultModel resultModel) throws Exception {
                                if (resultModel.isSuccess()) {
                                    return apiService.getGoodsMall(map);
                                }
                                ResultModel<List<ShopModel>> resultModel1 = new ResultModel<>();
                                resultModel1.setMsg(resultModel.getMsg());
                                return Observable.just(resultModel1);
                            }
                        });

        baseSubscribe(
                observable1
                , new NetParams(refresh > 1)
                , resultModel -> {
                    if (resultModel.isSuccess()&&resultModel.getData()!=null) {
                        notifyAllNewData(resultModel.getData(),oldDatas);
                    }else {
                        getView().getShopModelListResult(new ArrayList<>());
                    }

                });
    }

    private void notifyAllNewData(List<ShopModel> newDatas, List<ShopModel> oldDatas) {
        if (oldDatas != null && newDatas != null) {
            for (ShopModel oldData : oldDatas) {
                if (oldData.isChecked()) {
                    notifyNewData(newDatas, oldData.shop_id, -1);
                } else if (oldData.products != null) {
                    for (GoodsModel goodsModel : oldData.products) {
                        if (goodsModel.isChecked()) {
                            notifyNewData(newDatas, null, goodsModel.getId());
                        }
                    }
                }
            }
        }
        getView().getShopModelListResult(newDatas);
    }

    private void notifyNewData(List<ShopModel> newDatas, String shopId, int goodsCartId) {
        for (ShopModel newData : newDatas) {
            if (!TextUtils.isEmpty(shopId) && TextUtils.equals(shopId, newData.shop_id)) {
                newData.setChecked(true);
                return;
            }
            if (newData.products != null) {
                for (GoodsModel goodsModel : newData.products) {
                    if (goodsCartId > 0 && (goodsCartId == goodsModel.getId())) {
                        goodsModel.setChecked(true);
                        return;
                    }
                }
            }
        }
    }

    /**
     * 移除购物车商品
     *
     * @param goodsModelList
     */
    public void removeGoodList(List<GoodsModel> goodsModelList) {
        if (goodsModelList == null || goodsModelList.size() == 0) {
            return;
        }
        List<String> idList = new ArrayList<>();
        for (GoodsModel goodsModel : goodsModelList) {
            idList.add(goodsModel.getId() + "");
        }
        String cart_ids = TextUtils.join(",", idList);
        if (!UserRepository.isLogin()) {
            return;
        }
        cart_ids = String.format("[%s]", cart_ids);
        Observable<ResultModel> observable = apiService.removeGoodList(cart_ids, PushHelper.getRegistrationId(), UserInfo.getMemberId());

        baseSubscribe(observable
                , resultModel -> {
                    if (UserRepository.isLogin()) {//无人登录的情况下仍然显示数据
                        getView().removeGoodMallResult(resultModel, goodsModelList);
                    }
                });

    }


    /**
     * 更新商品属性
     *
     * @param map
     */
    public void updateGood(Map<String, Object> map) {
        if (!UserRepository.isLogin()) {
            return;
        }
        baseSubscribe(apiService.updateGood(map)
                , resultModel -> {
                    if (UserRepository.isLogin()) {
                        getView().updateGoodResult(resultModel);
                    }
                });
    }


}